﻿Namespace Framework
    Public MustInherit Class StickyUtilityCollection(Of TKey, TValue)
        Inherits System.Collections.ObjectModel.KeyedCollection(Of TKey, TValue)
        Implements IStickyComponent

        Private _AttachedTo As DependencyObject

        Public ReadOnly Property Mode() As AttachMode Implements IStickyComponent.Mode
            Get
                Return AttachMode.Immediate
            End Get
        End Property

        Public Sub OnAttach(ByVal sender As Object, ByVal e As System.EventArgs) Implements IStickyComponent.OnAttach
            If _AttachedTo Is Nothing Then
                _AttachedTo = sender
                For Each b As TValue In Me
                    StickyComponentManager.Attach(sender, b)
                Next
            End If
        End Sub

        Public Sub OnDetach(ByVal sender As Object, ByVal e As System.EventArgs) Implements IStickyComponent.OnDetach
            If _AttachedTo Is sender Then
                For Each b As TValue In Me
                    StickyComponentManager.Detach(sender, b)
                Next
                _AttachedTo = Nothing
            End If
        End Sub

        Protected Overrides Sub ClearItems()
            If _AttachedTo IsNot Nothing Then
                For Each b As TValue In Me
                    StickyComponentManager.Detach(_AttachedTo, b)
                Next
            End If
            MyBase.ClearItems()
        End Sub

        Protected Overrides Sub InsertItem(ByVal index As Integer, ByVal item As TValue)
            If _AttachedTo IsNot Nothing Then
                StickyComponentManager.Attach(_AttachedTo, item)
            End If
            MyBase.InsertItem(index, item)
        End Sub

        Protected Overrides Sub RemoveItem(ByVal index As Integer)
            If _AttachedTo IsNot Nothing Then
                Dim item As TValue = Me.Item(index)
                StickyComponentManager.Detach(_AttachedTo, item)
            End If
            MyBase.RemoveItem(index)
        End Sub

        Protected Overrides Sub SetItem(ByVal index As Integer, ByVal item As TValue)
            If _AttachedTo IsNot Nothing Then
                Dim oldItem As TValue = Me.Item(index)
                StickyComponentManager.Detach(_AttachedTo, oldItem)
                StickyComponentManager.Attach(_AttachedTo, item)
            End If
            MyBase.SetItem(index, item)
        End Sub
    End Class
End Namespace